<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">

      <sticky :class-name="'sub-navbar published'">
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">保存
        </el-button>
      </sticky>

      <div class="createPost-main-container">

        <el-row>

          <el-col :span="24">

            <div class="postInfo-container">
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="100px" label="分类:" class="postInfo-container-item">
                    <el-select v-model="postForm.category_id" placeholder="请选择" size="mini" @change="categoryChange">
                      <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <el-form-item label-width="140px" label="影片类型:">
                    <el-select v-model="postForm.video_type_id" size="mini" placeholder="请选择">
                      <el-option
                        v-for="item in videoTypeOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="影片类型关联排序:" class="postInfo-container-item">
                    <el-input-number v-model="postForm.relation_show_order" :min="1" :max="100" size="mini" />
                  </el-form-item>
                </el-col> -->
              </el-row>
              <!-- <el-row>
                <el-col :span="24">
                  <el-form-item label-width="100px" label="二级分类">
                    <table>
                      <tr v-for="(item, index) in optionComponents" :key="index">
                        <td>
                          <template>
                            <el-select v-model="postForm.category_options[index]['id']" filterable size="mini" placeholder="请选择">
                              <el-option
                                v-for="item in categoryOptionOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"/>
                            </el-select>
                          </template>
                        </td>
                        <td>
                          <el-button type="danger" size="mini" icon="el-icon-delete" @click="delTag(index)"/>
                        </td>
                      </tr>
                    </table>
                    <el-button type="success" size="mini" @click="addTag()">增加Tag</el-button>
                  </el-form-item>
                </el-col>
              </el-row> -->
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="元素名称:" class="postInfo-container-item">
                    <el-input v-model="postForm.name" auto-complete="off" size="mini"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="排序:" class="postInfo-container-item">
                    <el-input-number v-model="postForm.show_order" :min="1" :max="100" size="mini" />
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="100px" label="单位:" class="postInfo-container-item">
                    <el-input v-model="postForm.unit" auto-complete="off" size="mini"/>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="客户报价:" class="postInfo-container-item">
                    <el-input v-model="postForm.price" auto-complete="off" size="mini"/>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="100px" label="类型:" class="postInfo-container-item">
                    <el-select v-model="postForm.type" placeholder="请选择" size="mini">
                      <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="100px" label="等级:" class="postInfo-container-item">
                    <el-select v-model="postForm.level" placeholder="请选择" size="mini">
                      <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label-width="100px" label="描述:">
                <el-input :rows="1" v-model="postForm.desc" type="textarea" class="article-textarea" autosize placeholder="请输入内容"/>
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-form-item prop="url" style="margin-bottom: 10px;" label="封面图">
          <Upload v-model="postForm.url" />
        </el-form-item>

      </div>
    </el-form>

  </div>
</template>

<script>
import Vue from 'vue'
import Upload from '@/components/Upload/singleImage3'
import Sticky from '@/components/Sticky' // 粘性header组件
import { fetchElement, createElement, updateElement } from '@/api/elements'
import { fetchListAll, fetchOptionList } from '@/api/category'
import { fetchAllVideoTypes } from '@/api/videotype'

const defaultForm = {
  id: undefined,
  name: '',
  unit: '',
  show_order: 1,
  price: 0,
  type: 1,
  level: 1,
  state: 0,
  desc: '',
  url: '',
  video_type_id: -1,
  relation_show_order: 1,
  category_id: undefined,
  category_option_id: undefined,
  category_options: [{ id: '' }]
}

export default {
  name: 'ElementDetail',
  components: { Upload, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    currentId: {
      type: Number,
      default: undefined
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      optionComponents: [0],

      ignoreOptions: [{ value: 0, label: '否' }, { value: 1, label: '是' }],
      typeOptions: [{ value: 1, label: '角色' }, { value: 2, label: '设备' }],
      levelOptions: [{ value: 1, label: '初级' }, { value: 2, label: '中级' }, { value: 3, label: '高级' }],
      loading: false,
      videoTypeOptions: [],
      categoryOptions: [],
      categoryOptionOptions: [],
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateRequire }],
        unit: [{ required: true, trigger: 'blur', validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    }
  },
  watch: {
    currentId: {
      handler: function(val, oldval) {
        if (val !== undefined && val > 0) {
          this.fetchData(val)
        } else {
          this.postForm = Object.assign({}, defaultForm)
        }
      },
      deep: true
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.currentId
      this.fetchData(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
    this.fetchAllCategories()
    this.fetchVideoTypes()
  },
  methods: {
    fetchVideoTypes() {
      fetchAllVideoTypes().then(response => {
        this.videoTypeOptions = response.data.data.video_types
      })
    },
    addTag() {
      Vue.set(this.postForm.category_options, this.postForm.category_options.length, { id: '' })
      Vue.set(this.optionComponents, this.optionComponents.length, this.optionComponents[this.optionComponents.length - 1] + 1)
    },
    delTag(index) {
      this.postForm.tags.splice(index, 1)
      this.tagComponents.splice(index, 1)
    },
    fetchAllCategories() {
      fetchListAll({ 'result_type': 1 }).then(response => {
        this.categoryOptions = response.data.data.categories
      })
    },
    fetchCategoryOptions(cate_id) {
      fetchOptionList({ 'result_type': 1, 'category_id': cate_id }).then(response => {
        this.categoryOptionOptions = response.data.data
      })
    },
    categoryChange(val) {
      console.log('分类改变', val)
      this.fetchCategoryOptions(val)
    },
    fetchData(id) {
      fetchElement(id).then(response => {
        this.postForm = response.data.data
        console.log(this.postForm)
        // Set tagsview title
        // this.setTagsViewTitle()
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm() {
      this.postForm.display_time = parseInt(this.display_time / 1000)
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          let requestFunc = createElement
          let msg = '元素创建成功'
          if (this.postForm.id !== undefined && this.postForm.id > 1) {
            requestFunc = updateElement
            msg = '元素修改成功'
          }
          requestFunc(this.postForm).then(response => {
            const r = response.data
            console.log(r)
            if (r.code === 0) {
              this.$notify({
                title: '成功',
                message: msg,
                type: 'success',
                duration: 2000
              })
              this.postForm = Object.assign({}, defaultForm)
              this.$emit('successElementOperate')
            } else {
              this.$message({ message: r.msg, type: 'error' })
            }
          })
          this.loading = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/styles/mixin.scss";
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
